package com.atguigu.atcrowdfunding.controller;

import com.atguigu.atcrowdfunding.bean.Member;
import com.atguigu.atcrowdfunding.bean.Permission;
import com.atguigu.atcrowdfunding.bean.User;
import com.atguigu.atcrowdfunding.manager.service.UserService;
import com.atguigu.atcrowdfunding.potal.service.MemberService;
import com.atguigu.atcrowdfunding.util.AjaxResult;
import com.atguigu.atcrowdfunding.util.Const;
import com.atguigu.atcrowdfunding.util.MD5Util;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xzt
 * @create 2021-02-08 16:27
 */
@Controller
public class DispatcherController {

    @Autowired
    private UserService userService;

    @Autowired
    private MemberService memberService;

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request,HttpSession session){

        //判断是否需要自动登录
        //如果之前登录过，cookie中存放了用户信息，需要获取cookie中的信息，并进行数据库验证
        boolean needLogin = true;
        String logintype = null;
        Cookie[] cookies = request.getCookies();
        HashMap<String,Object> paramMap = new HashMap();
        if(cookies != null){//如果客户端禁用了cookie，则无法获取到Cookie的信息
            for (Cookie cookie : cookies) {
                if("logincode".equals(cookie.getName())){
                    String logincode = cookie.getValue();
                    String[] split = logincode.split("&");

                    if(split.length == 3){
                        String loginacct = split[0].split("=")[1];
                        String userpwd = split[1].split("=")[1];
                        logintype = split[2].split("=")[1];

                        paramMap.put("loginacct",loginacct);
                        paramMap.put("userpswd", userpwd);
                        paramMap.put("type",logintype);

                        if("user".equals(logintype)){
                            User user = userService.login(paramMap);
                            if(user != null){
                                session.setAttribute(Const.LOGIN_USER,user);
                                needLogin = false;
                            }

                            List<Permission> myPermissions = userService.queryPermissionByUserId(user.getId());
                            Set<String> myUris = new HashSet<>();//用于拦截器拦截许可权限
                            for (Permission myPermission : myPermissions) {
                                myUris.add("/"+myPermission.getUrl());
                            }
                            session.setAttribute(Const.MY_URIS,myUris);

                        }else if("member".equals(logintype)){
                            Member member = memberService.queryMemberLogin(paramMap);
                            if(member != null){
                                session.setAttribute(Const.LOGIN_MEMBER,member);
                                needLogin = false;
                            }

                        }

                    }

                }
            }
        }
        System.out.println(needLogin);
        if(needLogin){
            return "login";
        }else{
            if("user".equals(logintype)){
                return "redirect:/main.htm";
            }else if("member".equals(logintype)){
                return "redirect:/member.htm";
            }
        }
        return "login";
    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @RequestMapping("/member")
    public String member(){

        return "member/member";
    }

    @RequestMapping("/main")
    public String main(HttpSession session){

        try {
            //加载当前登录用户所拥有的权限
            User user = (User) session.getAttribute(Const.LOGIN_USER);

            List<Permission> myPermissions = userService.queryPermissionByUserId(user.getId());

            Permission permissionRoot = null;

            Map<Integer,Object> map = new HashMap<>();



            for (Permission myPermission : myPermissions) {
                map.put(myPermission.getId(),myPermission);
            }

            for (Permission myPermission : myPermissions) {

                Permission child = myPermission;

                if(child.getPid() == null){
                    permissionRoot = myPermission;
                }else{
                    Permission parent = (Permission) map.get(child.getPid());
                    parent.getChildren().add(child);
                }

            }

            session.setAttribute("permissionRoot",permissionRoot);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();//销毁session
        return "redirect:/index.htm";
    }

    //异步请求
    @ResponseBody
    @RequestMapping("/doLogin")
    public Object doLogin(String loginacct, String userpswd, String type,
                          HttpServletRequest request, String rememberme,
                          HttpServletResponse response){
        AjaxResult result = new AjaxResult();

        try {

            HashMap<String,Object> paramMap = new HashMap();
            paramMap.put("loginacct",loginacct);
            paramMap.put("userpswd", MD5Util.digest(userpswd));
            paramMap.put("type",type);
            HttpSession session = request.getSession();
            if("member".equals(type)){
                Member member = memberService.queryMemberLogin(paramMap);
                session.setAttribute(Const.LOGIN_MEMBER,member);

                if("1".equals(rememberme)){
                    String logincode = "\"loginacct="+member.getLoginacct()+"&userpwd="+member.getUserpswd()+"&logintype=member\"";

                    Cookie cookie = new Cookie("logincode", logincode);

                    cookie.setMaxAge(60*60*24*14);
                    cookie.setPath("/");//表示任何请求都可以访问Cookie
                    response.addCookie(cookie);

                }

            }else if("user".equals(type)){
                User user = userService.login(paramMap);
                session.setAttribute(Const.LOGIN_USER,user);

                if("1".equals(rememberme)){
                    String logincode = "\"loginacct="+user.getLoginacct()+"&userpwd="+user.getUserpswd()+"&logintype=user\"";

                    Cookie cookie = new Cookie("logincode", logincode);

                    cookie.setMaxAge(60*60*24*14);
                    cookie.setPath("/");//表示任何请求都可以访问Cookie

                    response.addCookie(cookie);
                }

                List<Permission> myPermissions = userService.queryPermissionByUserId(user.getId());
                Set<String> myUris = new HashSet<>();//用于拦截器拦截许可权限

                for (Permission myPermission : myPermissions) {
                    myUris.add("/"+myPermission.getUrl());
                }
                session.setAttribute(Const.MY_URIS,myUris);
            }else{

            }
            result.setData(type);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("登录失败!");
        }
        return result;
    }

    //同步请求
   /* @RequestMapping("/doLogin")
    public String doLogin(String loginacct, String userpswd, String type, HttpServletRequest request){

        HashMap<String,Object> paramMap = new HashMap();

        paramMap.put("loginacct",loginacct);
        paramMap.put("userpswd",userpswd);
        paramMap.put("type",type);

        User user = userService.login(paramMap);

        HttpSession session = request.getSession();
        session.setAttribute(Const.LOGIN_USER,user);

        return "redirect:/main.htm";
    }*/

    @RequestMapping("/doRegister")
    public String doRegister(Member member, Model model){
        userService.isRegister(member.getLoginacct());
        member.setUsername(member.getLoginacct());
        String userpswd = member.getUserpswd();
        String digest = MD5Util.digest(userpswd);
        member.setUserpswd(digest);
        userService.register(member);
        model.addAttribute("msg","注册成功");
        return "/login";
    }

}
